package converters;

import entidades.Laboratorio;
import entidades.LaboratorioPK;
import java.util.StringTokenizer;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import persistencia.RepositorioJPALaboratorio;


@FacesConverter(value = "LaboratorioConverter")
public class ConverterLaboratorio implements Converter {

	public RepositorioJPALaboratorio repositorio = new RepositorioJPALaboratorio();

	public Object getAsObject(FacesContext facesContext, UIComponent component,
			String submittedValue) {
		if (submittedValue.trim().equals("")) {
			return null;
		} else {
			try {
                                
        			LaboratorioPK number = new LaboratorioPK();
                                StringTokenizer st = new StringTokenizer(submittedValue);

                                number.setNumeroPredio(Integer.valueOf(st.nextToken()));
                                number.setNumero(Integer.valueOf(st.nextToken()));
                                Laboratorio laboratorio = repositorio.getById(number);
                                return laboratorio;

			} catch (NumberFormatException exception) {
				throw new ConverterException(new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Conversion Error",
						"Não é um laboratorio válido"));
			}
		}	
	}

	public String getAsString(FacesContext facesContext, UIComponent component,
			Object value) {
		if (value == null || value.equals("")) {
			return "";
		} else {
			return String.valueOf(((Laboratorio) value).getLaboratorioPK().getNumeroPredio())+"\t"+
                                String.valueOf(((Laboratorio) value).getLaboratorioPK().getNumero());
		}
	}

}